import { defineStore } from 'pinia'
import { localStorageGetItem } from '@/utils/local-storage-util.ts'
import { LS_SIDEBAR_BG_COLOR, LS_SIDEBAR_TEXT_COLOR } from '@/constant/local-storage-key.ts'
import { Menu } from '@/types'
import { computed, reactive, ref } from 'vue'

const storeSetup = () => {
  const collapse = ref(false)
  const bgColor = ref(localStorageGetItem(LS_SIDEBAR_BG_COLOR, '#324157'))
  const textColor = ref(localStorageGetItem(LS_SIDEBAR_TEXT_COLOR, '#bfcbd9'))
  const menus = reactive<Menu[]>([])

  const menuIds = computed(() => {
    return idsFromTree(menus)
  })

  const idsFromTree = (menus?: Menu[], ids?: string[]) => {
    if (!menus) return
    if (!ids) ids = []
    menus.forEach(menu => {
      ids.push(menu.id)
      idsFromTree(menu.children, ids)
    })
    return ids
  }

  const clearMenus = () => {
    menus.splice(0, menus.length)
  }
  const handleSetMenus = (value: Menu[]) => {
    clearMenus()
    menus.push(...value)
  }
  const handleSwitchCollapse = () => {
    collapse.value = !collapse.value
  }
  const handleSetCollapse = (value: boolean) => {
    collapse.value = value
  }

  return {
    collapse,
    bgColor,
    textColor,
    menus,
    menuIds,
    handleSetMenus,
    handleSwitchCollapse,
    handleSetCollapse,
  }
}
export const useSidebarStore = defineStore('sidebar', storeSetup)
